<?php
namespace Helpers;

use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysTree;

class Enum
{
    /**
     * 根据名称获取枚举内容
     *
     * @param $enumName
     * @return array|bool|mixed|null
     * @throws \Exception
     *
     * create by ck 20181112
     */
    public static function getEnum($enumName)
    {
        $cacheKey = 'enum_name_' . $enumName;
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $node = XhsysTree::findFirst([
            'conditions' => "sNodeName = '{$enumName}' AND iNodeType = 2 AND bDelete = 0"
        ]);
        if (!$node) {
            throw new \Exception('枚举不存在');
        }
        $enumList = self::getEnumByNodeId($node->iNodeId);
        Cache::save($cacheKey, $enumList);
        return $enumList;
    }

    /**
     * 根据节点id获取枚举
     *
     * @param $nodeId
     * @return array|bool|mixed|null
     *
     * create by ck 20181112
     */
    private static function getEnumByNodeId($nodeId)
    {
        $cacheKey = 'enum_name_' . $nodeId;
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $enumList = XhsysEnum::find([
            'conditions' => "iNodeId = {$nodeId} AND bDelete = 0",
            'columns' => 'sEnumValue,sEnumName'
        ])->toArray();
        $enumList = array_column($enumList, 'sEnumName', 'sEnumValue');
        Cache::save($cacheKey, $enumList);
        return $enumList;
    }
}